<template>
    <p v-show="!loading" class="update__picker" @click="handleClick">检查版本更新</p>
    <p v-show="loading" class="update__picker">版本更新检查中......</p>
    <p class="now__version">当前版本：v{{ nowVersion }}</p>
    <n-modal v-model:show="showModal" :close-on-esc="false" :mask-closable="false">
        <n-card style="width: 400px" title="软件更新中" :bordered="false" size="huge" role="dialog" aria-modal="true">
            <div class="updataer__warning--text">
                <n-icon size="16" color="#FFA500">
                    <WarningOutline></WarningOutline>
                </n-icon>
                <p>软件更新中，请勿退出！</p>
            </div>
            <n-progress :color="{ stops: ['#E3F2FD', '#2080f0'] }" type="line" :percentage="processingComputed"
                indicator-placement="inside" processing />
        </n-card>
    </n-modal>
</template>

<script setup lang='ts'>
import { check } from '@tauri-apps/plugin-updater';
import { relaunch } from '@tauri-apps/plugin-process';
import { invoke } from "@tauri-apps/api/core";
import { useMessage } from 'naive-ui';
import { WarningOutline } from '@vicons/ionicons5';
const loading = ref(false);
const showModal = ref(false);
const donwloadNumber = ref(0);
const totalLoadNumber = ref(0);
const message = useMessage();
const processingComputed = computed(() => {
    if (totalLoadNumber.value === 0) return 0;
    return Math.floor(donwloadNumber.value * 100 / totalLoadNumber.value);
})
const nowVersion = ref('');
const getVersionInfo = async () => {
    try {
        const version = await invoke('get_app_version');
        nowVersion.value = version as string;
    } catch (error) {
        nowVersion.value = '未知版本'
    }
}
getVersionInfo();
// 更新
const handleClick = async () => {
    try {
        loading.value = true;
        const update = await check();
        if (update) {
            showModal.value = true;
            let downloaded = 0;
            let contentLength = 0;
            // alternatively we could also call update.download() and update.install() separately
            await update.downloadAndInstall((event) => {
                switch (event.event) {
                    case 'Started':
                        contentLength = event.data.contentLength || 0;
                        totalLoadNumber.value = contentLength;
                        break;
                    case 'Progress':
                        downloaded += event.data.chunkLength;
                        donwloadNumber.value = downloaded;
                        break;
                    case 'Finished':
                        console.log('download finished');
                        break;
                }
            });
            message.success('更新完成！');
            await relaunch();
        }
    } catch (error: any) {
        showModal.value = false;
        if (error === 'Could not fetch a valid release JSON from the remote') {
            return message.warning(`v${nowVersion.value}已经是最新版本`);
        }
        message.warning(`更新出错：${error?.message || error || '请求错误'}`);
    } finally {
        loading.value = false;
    }
}
</script>
<style scoped lang='scss'>
.update__picker {
    margin: 1rem 0 0.5rem;
    color: #4090EF;
    text-align: center;
    cursor: pointer;
}

.now__version {
    text-align: center;
    font-size: 0.75rem;
}
.updataer__warning--text{
    display: flex;
    align-items: center;
    margin-bottom: 1rem;
    color:#FFA500;
    gap:12px;
}
</style>